-- UIFateChainList
-- Create by cheny3 Nov/24/2016
-- 命运的链列表

-- UIFateChainList继承自Layer
UIFateChainList = class("UIFateChainList", function()
    return cc.Layer:create();
end);

function UIFateChainList.create()
    return UIFateChainList.new();
end

-- 内部函数声明

-- 标签页
local TAB_TYPE_LIST = {};

-- 构造函数
function UIFateChainList:ctor()
    -- 初始化
    self:setName("UIFateChainList");

    -- 复用世界树果实模板
    local node = cc.CSLoader:createNode("layout/talent/TalentFruitBonus.csb");
    self:addChild(node);
    self.node = node;

    local CT = node:getChildByName("CT");
    local scrollview = CT:getChildByName("scrollview");
    local line1 = CT:getChildByName("line1");
    local line3 = CT:getChildByName("line3");
    scrollview:setVisible(false);
    line1:setVisible(false);
    line3:setVisible(true);

    scrollview = CT:getChildByName("scrollview2");
    self.CT = CT;
    self.scrollView = scrollview;
    self.scrollView:setVisible(true);
    self.oriHeight = self.scrollView:getInnerContainerSize().height;

    -- 修改滚动方向
    -- 1 垂直
    -- 2 水平
    self.scrollView:setDirection(1);

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 初始化
    self:init();

    -- 标签页
    self:redrawTabs();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UIFateChainList:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 标签页图片
function UIFateChainList:getTabIcon(fateType)
    local iconList = {
        [FATE_CHAIN_TYPE_NORMAL]  = getFateChainIconPath("type1"),  -- 普通
        [FATE_CHAIN_TYPE_CLOSE]   = getFateChainIconPath("type2"),  -- 亲密
        [FATE_CHAIN_TYPE_INHERIT] = getFateChainIconPath("type3"),  -- 传承
        [FATE_CHAIN_TYPE_LOVER]   = getFateChainIconPath("type4"),  -- 恋人
        [FATE_CHAIN_TYPE_ENEMY]   = getFateChainIconPath("type5"),  -- 宿敌
    };

    return iconList[fateType];
end

-- 绘制标签页
function UIFateChainList:redrawTabs()
    local tabNode = findChildByName(self.node, "CT/tab");
    local bubbleParent = findChildByName(self.node, "CT/bubble_parent");
    bubbleParent:setVisible(true);

    -- 标签页数量
    local tabNum = #TAB_TYPE_LIST;

    -- 先移除旧的标签
    tabNode.rows = {};
    tabNode:removeAllChildren();
    bubbleParent:removeAllChildren();

    -- 根据tab数据，生成新标签
    local widget = replaceNodeWithWidget(cc.CSLoader:createNode("layout/tab/tab.csb"));
    local bubbleWidget = replaceNodeWithWidget(cc.CSLoader:createNode("layout/common/BlueBubble.csb"));

    -- 置灰颜色
    local blendColor = TextStyleM.TEXT_COLOR_BLEND;
    local normalColor = TextStyleM.TEXT_COLOR_NORMAL;

    for i = 1, tabNum do
        local child = widget:clone();
        local bubble = bubbleWidget:clone();
        child:setName("tab" .. i);
        child.index = i;

        self:registerTabTouchEvent(child);

        -- 计算单元格坐标
        -- 这个坐标将是单元格的描点所在
        local x = (i - 1) * 68 + 55;
        local y = 75;

        child:setPositionX(x);
        child:setPositionY(y);
        bubble:setPositionX(x + 25);
        bubble:setPositionY(-30);
        child.type = TAB_TYPE_LIST[i];
        bubble.type = TAB_TYPE_LIST[i];
        bubble:setVisible(false);

        local tabLight = findChildByName(child, "light");
        local tabImage = findChildByName(child, "tab");
        tabLight:setScaleX(0.7);
        tabImage:setScaleX(0.7);

        local tabText = findChildByName(child, "text");
        local tabIcon = findChildByName(child, "icon");

        tabText:setVisible(false);

        if self.type == TAB_TYPE_LIST[i] then
            tabLight:setVisible(true);
            tabIcon:setColor(normalColor);
            tabImage:setColor(normalColor);
        else
            tabLight:setVisible(false);
            tabIcon:setColor(blendColor);
            tabImage:setColor(blendColor);
        end

        tabIcon:loadTexture(self:getTabIcon(TAB_TYPE_LIST[i]));
        tabNode:addChild(child);
        bubbleParent:addChild(bubble);
        table.insert(tabNode.rows, child)
    end

    for i = 1, #tabNode.rows do
        local tab = tabNode.rows[i];
        tab:setPositionY(tab:getPositionY() + 100);
    end

    performWithDelay(self, function() self:playTabEffect(); end, 0.2);
end

-- 页签动画效果
function UIFateChainList:playTabEffect()
    local tabNode = findChildByName(self.node, "CT/tab");
    -- 带窗口动画播放结束后，页签从上面往下掉
    for i = 1, #tabNode.rows do
        local tab = tabNode.rows[i];
        local pos = cc.p(tab:getPosition());
        local delay = cc.DelayTime:create(0.15 * (i - 1));
        local moveDown = cc.MoveTo:create(0.15, cc.p(pos.x, pos.y - 100 - 5));
        local moveBack = cc.MoveTo:create(0.15, cc.p(pos.x, pos.y - 100));
        local action = cc.Sequence:create(delay, moveDown, moveBack);
        tab:runAction(action);
    end

    tabNode:setVisible(true);

    performWithDelay(self.node, function() self:checkTip(true); end, 0.15 * (#tabNode.rows));
end

-- 注册标签页点击回调
function UIFateChainList:registerTabTouchEvent(node)
    -- 节点
    local tabImage = node:getChildByName("tab");
    local tabLight = node:getChildByName("light");
    local tabIcon = node:getChildByName("icon");
    local tabNode = findChildByName(self.node, "CT/tab");

    -- 置灰颜色
    local blendColor = TextStyleM.TEXT_COLOR_BLEND;
    local normalColor = TextStyleM.TEXT_COLOR_NORMAL;

    local function onClick(sender, eventType)
        -- 点击时的回调
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            -- 去除其它高亮
            for i = 1, #tabNode.rows do
                tabNode.rows[i]:getChildByName("light"):setVisible(false);
                tabNode.rows[i]:getChildByName("tab"):setColor(blendColor);
                tabNode.rows[i]:getChildByName("icon"):setColor(blendColor);
            end
            -- 设置本身高亮
            tabLight:setVisible(true);
            tabImage:setColor(normalColor);
            tabIcon:setColor(normalColor);

            -- 设置当前
            self.type = node.type;

            -- 重绘
            self:redraw();
        end
    end
    tabImage:addTouchEventListener(onClick);
end

-- 初始化
function UIFateChainList:init()
    -- 标签页内容
    local ret = {};
    for _, fateType in ipairs(FateChainM.getAllGroupType()) do
        local list = FateChainM.getFateListByType(fateType);
        if #list > 0 then
            -- 有数据的才显示
            table.insert(ret, fateType);
        end
    end
    TAB_TYPE_LIST = ret;
    self.type = TAB_TYPE_LIST[1];
end

-- 重绘
function UIFateChainList:redraw()
    -- 标题
    local title1 = findChildByName(self.node, "CT/title1");
    title1:setVisible(true);
    title1:setString(getLocStr("title_fate_chain"));
    TextStyleM.setTitleStyle(title1);

    -- 副标题
    local title2 = findChildByName(self.node, "CT/title2");
    title2:setVisible(true);
    TextStyleM.setSubheadStyle(title2);
    title2:setString(getLocStr("fate_type_" .. self.type));
    title2.oriPosY = title2.oriPosY or title2:getPositionY();
    title2:setPositionY(title2.oriPosY - 10);

    -- 两侧花纹
    local subBgL = findChildByName(self.node, "CT/sub_bg_l");
    local subBgR = findChildByName(self.node, "CT/sub_bg_r");
    subBgL:loadTexture(getTitleBgIconPath("upgrade"));
    subBgR:loadTexture(getTitleBgIconPath("upgrade"));

    -- 绘制内容
    self:redrawSlimeLines();

    self.scrollView:jumpToTop();
end

-- 绘制Top横线
-- 为了防止滚动穿帮，先这么处理
function UIFateChainList:redrawTopLines(totalHeight)
    local lineNode = cc.CSLoader:createNode("layout/setting/NotifyNode.csb");
    local widget = replaceNodeWithWidget(lineNode);

    local child = widget:clone();
    local line = child:getChildByName("line");

    for _, node in pairs(child:getChildren()) do
        node:setVisible(false);
    end
    line:setScale(1);
    line:setVisible(true);
    child:setAnchorPoint(cc.p(0.5, 0.5));
    child:setPositionX(25);
    child:setPositionY(totalHeight - 25);

    self.scrollView:addChild(child);
end

-- 排序
local sortSlimeList;
sortSlimeList = function(a, b)
    -- 可以领奖的挪到前面
    if a.state == FATE_CHAIN_FINISH and b.state ~= FATE_CHAIN_FINISH then
        return true;
    elseif a.state ~= FATE_CHAIN_FINISH and b.state == FATE_CHAIN_FINISH then
        return false;
    end

    return a.id < b.id;
end

-- 绘制冈布奥条目
function UIFateChainList:redrawSlimeLines()
    -- 去除所有
    self.scrollView:removeAllChildren();

    local lineNode = cc.CSLoader:createNode("layout/setting/NotifyNode.csb");
    local widget = replaceNodeWithWidget(lineNode);

    -- 获取所有信息
    local slimeList = FateChainM.getFateListByType(self.type);
    table.sort(slimeList, sortSlimeList);

    -- 计算容器高度
    local needHeight = #slimeList * 60 + 30;
    local totalHeight = math.max(self.oriHeight, needHeight);

    self.scrollView:setInnerContainerSize(cc.size(self.scrollView:getInnerContainerSize().width, totalHeight));

    -- 绘制顶部横线
    self:redrawTopLines(totalHeight);

    -- 宠物节点
    local petItem = cc.CSLoader:createNode("layout/sky_city/SmallPetNode.csb");
    -- 循环复用
    local petWidget = replaceNodeWithWidget(petItem);

    for i = 1, #slimeList do
        local child = widget:clone();
        local icon = child:getChildByName("icon");
        local text =  child:getChildByName("text");
        local bubble = child:getChildByName("bubble");
        local line = child:getChildByName("line");
        local mask = child:getChildByName("mask");
        local light = child:getChildByName("light");
        line:setScaleX(1);
        local y = (i - 1) * -60 + totalHeight - 80;
        child:setPositionX(25);
        child:setPositionY(y);
        child:setVisible(true);
        mask:setPositionX(-6);
        light:setVisible(false);
        icon:setAnchorPoint(cc.p(0.5, 0.5));

        -- 信息
        local info = slimeList[i];

        local state = info["state"];

        local iconPath = getLevelItemIconPath(info["icon"]);
        local opacityValue = 128;
        local lightMode = false;
        local textColor = TextStyleM.TEXT_COLOR_DARK_BROWN;
        local posY = 38;
        local posX = 20;
        if state >= FATE_CHAIN_BONUS then
            -- 已经领取了的，用开启图标
            iconPath = getLevelItemIconPath(info["open_icon"]);
        elseif state == FATE_CHAIN_FINISH then
            -- 完成的，不透明
            opacityValue = 255;
            textColor = TextStyleM.TEXT_COLOR_BLUE;
            light:setVisible(true);
            local rotateForever = cc.RepeatForever:create(cc.RotateBy:create(30, 360));
            light:runAction(rotateForever);

            playBubbleAnima2(icon, false, 0.5);
        elseif state == FATE_CHAIN_UNFINISH then
            -- 未完成的，去色
            lightMode = true;
            textColor = TextStyleM.TEXT_COLOR_GRAY;
        end

        icon:loadTexture(iconPath);
        icon:setScale(0.5);
        icon:setPosition(cc.p(posX, posY));

        if lightMode then
            setGrayTransMode(icon, lightMode);
        end
        icon:setOpacity(opacityValue);

        TextStyleM.setTextStyle(text, TextStyleM.TEXT_SIZE_SMALL, textColor);
        text:setString(info["name"]);

        bubble:setVisible(false);

        -- 显示组合
        local group = info["group"] or {};
        table.sort(group, function(a, b) return a > b; end);
        for index, petId in ipairs(group) do
            local icon = PetM.getDefaultIcon(petId);
            local iconPath = getSmallHeroIconPath(icon);

            local petItem = petWidget:clone();
            local iconImg = petItem:getChildByName("icon");
            iconImg:loadTexture(iconPath);

            if state == FATE_CHAIN_UNFINISH then
                -- 未完成的用剪影
                -- 没有的用剪影
                if not PetM.getMyPet(petId) then
                    iconPath = getHeroSilhouetteSmallIconPath(icon);
                    iconImg:loadTexture(iconPath);
                else
                    setGrayTransMode(iconImg, true);
                end
            end

            -- 计算位置
            child:addChild(petItem);
            petItem:setPosition(cc.p(posX, posY));
            petItem:setScale(0.8);
            petItem:setPosition(cc.p(bubble:getPositionX() - index * 38 + 75, bubble:getPositionY()));
        end

        local panel = findChildByName(child, "panel");
        local function onClick(sender, eventType)
            -- 点击时的回调
            if eventType == ccui.TouchEventType.ended then
                AudioM.playFx("button_click");
                self:clickItem(info);
            end
        end
        panel:addTouchEventListener(onClick);
        self.scrollView:addChild(child);
    end
end

-- 点击项目
function UIFateChainList:clickItem(info)
    local title = info["name"];
    local state = info["state"];
    local desc = getLocStr("fate_chain_bonus");
    local okBtnEnable = false;
    local fateHero = nil;
    local detailDesc = FateChainM.getBonusDetailDesc(info["id"]);
    btnText = getLocStr("btn_text_take_bonus2");

    -- 冈布奥名称
    local groups = info["group"];
    table.sort(groups);
    for index, petId in ipairs(groups) do
        if state ~= FATE_CHAIN_UNFINISH or PetM.getMyPet(petId) then
            -- 已经完成了的，或者有冈布奥，直接显示名称
            if state == FATE_CHAIN_FINISH then
                desc = desc .. "[blue]" .. PetM.query(petId, "name") .. "[-]";
            else
                desc = desc .. "[gray]" .. PetM.query(petId, "name") .. "[-]";
            end
        else
            -- 显示未知冈布奥
            desc = desc .. "[gray]" .. getLocStr("unknow_slime") .. "[-]";
        end

        if index ~= #info["group"] then
            desc = desc .. "\n";
        end
    end

    if state == FATE_CHAIN_FINISH then
        -- 已经完成的，设置成可点
        okBtnEnable = true;
    elseif state >= FATE_CHAIN_BONUS then
        -- 已领取
        btnText = getLocStr("btn_text_complete");
    end

    local function okFunc()
        if state == FATE_CHAIN_FINISH then
            FateChainM.takeFateChainBonus(info["id"]);
        end
    end

    local args = FateChainM.queryGroup(info["id"], "args");
    if args["limit_pet"] then
        fateHero = args["limit_pet"];
    end

    -- 提示内容
    local bonusShow = FateChainM.queryGroup(info["id"], "bonus_show");
    if type(bonusShow) ~= "table" then
        bonusShow = FateChainM.queryGroup(info["id"], "bonus")["bonus"];
    end

    -- 用奖励提示框
    showBonusNotifyForm(title, bonusShow, okFunc, desc, btnText, okBtnEnable, true, nil,
        {["detailDesc"] = detailDesc, ["fateHero"] = fateHero, ["bottomMargin"] = 60});
end

-- 注册事件处理回调函数
function UIFateChainList:registerEventCallback()
    -- 注册获得焦点的回调
    EventMgr.register("UIFateChainList", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIFateChainList" then
        elseif para["lose"] == "UIFateChainList" then
        end
    end);

    -- 领奖事件
    EventMgr.register("UIFateChainList", event.FATE_CHAIN_TAKE_BONUS, function(para)
        local id = para.id;
        -- 弹字
        local msg = "";
        local bonus = FateChainM.queryGroup(id, "bonus");
        local alert = FateChainM.queryGroup(id, "alert");
        local showBonus = FateChainM.queryGroup(id, "bonus_show");
        if type(alert) == "string" and string.len(alert) > 0 then
            -- 配置了弹字
            msg = alert;
        elseif bonus["bonus"] then
            -- 奖励类的
            local name = "";
            local count = 0;
            for _, perBonus in ipairs(bonus["bonus"]) do
                if perBonus[1] == 1 then
                    name = ItemM.query(perBonus[2], "name");
                elseif perBonus[1] == 2 then
                    name = FieldsM.query(perBonus[2],"name");
                end
                count = perBonus[3];
                msg = msg .. string.format(getLocStr("item_bonus_format2"), name, count) .. "\n";
            end
        elseif bonus["props"] then
            -- 属性类的
            local bonusDesc = FateChainM.queryGroup(id, "bonus_desc");
            if type(bonusDesc) == "string" and string.len(bonusDesc) > 0 then
                -- 配置了描述
                msg = bonusDesc;
            elseif type(showBonus) == "table" and #showBonus > 0 then
                -- 冈布奥宝宝+1
                if showBonus[1][1] == "baby" then
                    local name = FateChainM.queryBaby(showBonus[1][2], "name");
                    local count = showBonus[1][3];
                    msg = string.format(getLocStr("item_bonus_format2"), name, count);
                end
            end
        end

        local list = splitString(msg, "\n");
        splitAlert(list);
        self:redraw();
        self:checkTip();
    end);

    -- 关注服务器状态更新事件
    EventMgr.register("UIFateChainList", event.SERVER_STATUS_UPDATE, function(para)
        local data = para.data;
        if data["fate_chain_open"] ~= 1 then
            -- 命运之链禁止
            UIMgr.getCurrentScene():removeFormByName("UIFateChainList");
        end
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UIFateChainList 界面析构清理");
            EventMgr.removeAll("UIFateChainList");
        elseif eventType == "enter" then

        end
    end);
end

-- 注册点击事件
function UIFateChainList:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIFateChainList");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 更多按钮
    local btnSet = findChildByName(self.node, "BT/take_bonus");
    btnSet:setVisible(false);
end

-- 检查提示
function UIFateChainList:checkTip(effect)
    local bubbleParent = findChildByName(self.node, "CT/bubble_parent");
    for _, child in ipairs(bubbleParent:getChildren()) do
        if FateChainM.hasBonusToTakeByType(child.type) then
            child:setVisible(true);
            checkBlueBubbleStatus(child, true, 0.60);
            if effect then
                local bg = findChildByName(child, "bg");
                bg:setOpacity(0);
                local fadeIn = cc.FadeIn:create(0.4);
                bg:runAction(fadeIn);
            end
        else
            child:setVisible(false);
        end
    end
end